package leetcode.code1462;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;

public class Solution implements IDebug {

	public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) {
		// 建立前置课程图:前置课->课
		int len = prerequisites.length;
		Map<Integer, List<Integer>> edges = new HashMap<>();// 边集合
		int[] ins = new int[numCourses];// 课程入度
		this.buildGraph(len, prerequisites, edges, ins);
		// 建立到达关系
		boolean[][] reach = new boolean[numCourses][numCourses];// reach[a][b]=true表示有从a到b的路，a为b的前置
		// 准备宽度优先搜索
		Queue<Integer> queue = new LinkedList<>();
		for (int i = 0; i < numCourses; i++) {
			int in = ins[i];// 面壁思过
			if (in == 0 && edges.containsKey(i)) {// if(疑似前置课程 && 有后续课程){确认是前置课程}
				queue.add(i);// 面壁思过，入度添加到队列，错的离谱
			}
		}
		Map<Integer, Set<Integer>> preCourses = new HashMap<>();
		Set<Integer> preCourse = null;
		while (!queue.isEmpty()) {
			int course = queue.poll();
			preCourse = preCourses.getOrDefault(course, new HashSet<>());
			for (int pre : preCourse) {
				reach[pre][course] = true;
			}
			preCourse.add(course);
			List<Integer> edge = edges.getOrDefault(course, null);
			if (edge == null) {
				continue;
			}
			for (int to : edge) {
				int in = --ins[to];
				Set<Integer> preCourse4to = preCourses.getOrDefault(to, new HashSet<>());
				preCourse4to.addAll(preCourse);
				preCourses.put(to, preCourse4to);
				if (in == 0) {
					queue.add(to);
				}
			}
		}
		// 到reach表中找答案
		int queryLen = queries.length;
		List<Boolean> ans = new ArrayList<>();
		for (int i = 0; i < queryLen; i++) {
			int[] query = queries[i];
			int from = query[0], to = query[1];
			ans.add(reach[from][to]);
		}
		return ans;
	}

	private void buildGraph(int len, int[][] prerequisites, Map<Integer, List<Integer>> edges, int[] ins) {
		for (int i = 0; i < len; i++) {
			int[] pre = prerequisites[i];
			int courseStart = pre[0], courseEnd = pre[1];
			List<Integer> edge = edges.getOrDefault(courseStart, new ArrayList<>());// 取出class1的边集
			edge.add(courseEnd);// 添加新边
			edges.put(courseStart, edge);
			ins[courseEnd]++;// 入度增加1
		}
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		List<Boolean> result = this.checkIfPrerequisite(2, HelpDebug.str2array1("[[1,0]]"), HelpDebug.str2array1("[[0,1],[1,0]]"));
		for (boolean res : result) {
			System.out.println(res);
		}
	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
